#include "Directory.h"

Directory::Directory(FileSystem* fs, Inode * inode, std::string name) :
	OpenFile(fs, inode, name) {
	if ((inode->getType() & X_IFMT) != X_IFDIR)
		throw("The directory " + name + " does not exist.");
}

Directory::~Directory() {
}

Inode* Directory::findFile(const char* filename) {
	short inodeNr = 0;
	std::string tmpFilename;
	bool gevonden = false;

	for (long i = 0; i < inode->getFileSize(); i += 512) {
		byte* buffer;
		Blok* bl = filesystem->getBlok(inode->getBlocknummer(i));

		buffer = bl->getBytes();

		for (int i = 0; i < 512; i += 16) {
			inodeNr = getshort(buffer, i);
			tmpFilename = getchars(buffer, i + 2, 14);

			if (tmpFilename == filename) {
				gevonden = true;
				break;
			}
		}

		if (gevonden)
			break;
	}
	if (gevonden)
		return filesystem->findInodeByNumber(inodeNr);

	else
		throw("File not found.");

}

std::map<std::string, long>* Directory::getInodeNummerLijst() {
	std::map<std::string, long>* tmpList = new map<std::string, long> ();

	for (long i = 0; i < inode->getFileSize(); i += 512) {
		byte* buffer;

		Blok* bl = filesystem->getBlok(inode->getBlocknummer(i));

		buffer = bl->getBytes();

		for (int i = 0; i < 512; i += 16) {
			if (getshort(buffer, i) != 0) {
				tmpList->insert(map<std::string, long>::value_type(getchars(
						buffer, i + 2, 14), getshort(buffer, i)));
			}
		}
	}

	return tmpList;
}
